<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="品牌" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="brand">
              <a-input v-model="model.brand" placeholder="请输入品牌"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="FC NO" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="fcno">
              <a-input v-model="model.fcno" placeholder="请输入FC NO"  ></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
        <div class='add-box'>
          <a-button type="link" icon="plus" @click='addCavity'>添加预混分布</a-button>
        </div>
        <div v-if="model.eneDistributions.length > 0" >
          <div class='cavity-box' v-for='(item,index) in model.eneDistributions' :key="index" v-if='model.eneDistributions.length>0'>
            <div class='title-box'>
              <span>预混分布{{ alphabetizedItems[index].letter }}</span>
              <a-popconfirm title="确定删除吗?" @confirm="() => deleteCavity(index)">
                <a-button type="link" icon="minus">删除预混分布</a-button>
              </a-popconfirm>
            </div>
            <a-row>
              <a-col :span="24">
                <a-form-model-item :labelCol="labelCol3" :wrapperCol="wrapperCol3" :prop="'eneDistributions[' + index + '].enePremixDistributions'">
                  <a-row>
                    <a-col :span="24">
                      <a-form-model-item label="" :labelCol="labelCol" :wrapperCol="wrapperCol3">
                        <div class='mark-infos'>
                          <a-table
                            ref="markTable"
                            size="middle"
                            :scroll="{x:false,y:false}"
                            bordered
                            :rowKey="(record = () => record.id)"
                            :columns="columns"
                            :dataSource="item.enePremixDistributions"
                            :pagination="false"
                            :loading="loading"
                            class="j-table-force-nowrap1">
                            <template v-for="col in ['materialCode','material','moisture','density','formulationVolume','effectiveVolume']" :slot="col" slot-scope="text, record, indx">
                              <div :key="record.id">
                                <a-form-model-item :prop="'eneDistributions[' + index + '].enePremixDistributions['+indx+'].materialCode'" v-if="col==='materialCode'">
                                  <a-input placeholder='请输入材料代码' v-model="record.materialCode" disabled/>
                                </a-form-model-item>
                                <a-form-model-item :prop="'eneDistributions[' + index + '].enePremixDistributions['+indx+'].material'" v-else-if="col==='material'">
                                  <j-search-select-tag
                                    type="list"
                                    v-model="record.material"
                                    dict="ene_ingredient_management,material_description,id"
                                    placeholder="请选择材料"
                                  />
                                </a-form-model-item>
                                <a-form-model-item :prop="'eneDistributions[' + index + '].enePremixDistributions['+indx+'].moisture'" v-else-if="col==='moisture'">
                                  <a-input placeholder='请输入水分' v-model="record.moisture" />
                                </a-form-model-item>
                                <a-form-model-item :prop="'eneDistributions[' + index + '].enePremixDistributions['+indx+'].density'" v-else-if="col==='density'">
                                  <a-input placeholder='请输入密度' v-model="record.density" @input="onCellChange(record)" />
                                </a-form-model-item>
                                <a-form-model-item :prop="'eneDistributions[' + index + '].enePremixDistributions['+indx+'].formulationVolume'" v-else-if="col==='formulationVolume'">
                                  <a-input v-model="record.formulationVolume" disabled/>
                                </a-form-model-item>
                                <a-form-model-item :prop="'eneDistributions[' + index + '].enePremixDistributions['+indx+'].effectiveVolume'" v-else-if="col==='effectiveVolume'">
                                  <a-input placeholder='请输入有效容积' v-model="record.effectiveVolume" />
                                </a-form-model-item>
                              </div>
                            </template>
                          </a-table>
                        </div>
                      </a-form-model-item>
                    </a-col>
                  </a-row>
                </a-form-model-item>
              </a-col>
            </a-row>
          </div>
        </div>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

import { httpAction, getAction, postAction } from '@/api/manage'
  import { validateDuplicateValue } from '@/utils/util'

  export default {
    name: 'EnePremixForm',
    components: {
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        model:{
          eneDistributions: [
            {
              enePremixDistributions: [
                {
                  id:'',
                  materialCode:'',
                  material:'',
                  moisture:'',
                  density:'',
                  formulationVolume:'',
                  effectiveVolume:'',
                },
                {
                  id:'',
                  materialCode:'',
                  material:'',
                  moisture:'',
                  density:'',
                  formulationVolume:'',
                  effectiveVolume:'',
                },
                {
                  id:'',
                  materialCode:'',
                  material:'',
                  moisture:'',
                  density:'',
                  formulationVolume:'',
                  effectiveVolume:'',
                },
                {
                  id:'',
                  materialCode:'',
                  material:'',
                  moisture:'',
                  density:'',
                  formulationVolume:'',
                  effectiveVolume:'',
                },
              ]
            }
          ]
         },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        labelCol1: {
          xs: { span: 24 },
          sm: { span: 3 },
        },
        wrapperCol1: {
          xs: { span: 24 },
          sm: { span: 21 },
        },
        labelCol2: {
          xs: { span: 24 },
          sm: { span: 7 },
        },
        wrapperCol2: {
          xs: { span: 24 },
          sm: { span: 17 },
        },
        labelCol3: {
          xs: { span: 24 },
          sm: { span: 3},
        },
        wrapperCol3: {
          xs: { span: 24 },
          sm: { span: 24 },
        },
        confirmLoading: false,
        validatorRules: {
        },
        columns: [
          {
            title: '序号',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title: '材料代码',
            align: "center",
            dataIndex: 'materialCode',
            scopedSlots: { customRender: 'materialCode' }
          },
          {
            title:'材料',
            align:"center",
            dataIndex: 'material',
            width:180,
            scopedSlots: { customRender: 'material' }
          },
          {
            title:'水分（%）',
            align:"center",
            dataIndex: 'moisture',
            scopedSlots: { customRender: 'moisture' }
          },
          {
            title:'密度',
            align:"center",
            dataIndex: 'density',
            scopedSlots: { customRender: 'density' }
          },
          {
            title:'配方容积',
            align:"center",
            dataIndex: 'formulationVolume',
            scopedSlots: { customRender: 'formulationVolume' }
          },
          {
            title:'有效容积',
            align:"center",
            dataIndex: 'effectiveVolume',
            scopedSlots: { customRender: 'effectiveVolume' }
          },
        ],
        dataSource:[],
        timer: null,
        loading: false,
        url: {
          add: "/craft/enePremix/add",
          edit: "/craft/enePremix/edit",
          queryById: "/craft/enePremix/queryById"
        }
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
      alphabetizedItems() {
        const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        return this.model.eneDistributions.map((item, index) => ({
          letter: letters[index % letters.length], // 循环使用字母
          originalIndex: index, // 保留原始索引用于删除操作
          item // 也可以直接包含item对象，或者根据需要处理
        }));
      }
    },
    created () {
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
      onCellChange(record) {
        if (record) {
          postAction('/craft/enePremix/compute/formula', record ).then(
            (res) => {
              if (res.success) {
                this.$set(record, 'formulationVolume', res.result)
                if(res.result === null){
                  alert('未选择材料');
                }
              }
            }
          )
        }
      },
      add () {
        this.edit(this.modelDefault);
      },
      edit (record) {
        if(record===undefined){
          this.model = {
            eneDistributions:[
              {
                enePremixDistributions:[
                  {
                    id:'',
                    materialCode:'',
                    material:'',
                    moisture:'',
                    density:'',
                    formulationVolume:'',
                    effectiveVolume:'',
                  },
                  {
                    id:'',
                    materialCode:'',
                    material:'',
                    moisture:'',
                    density:'',
                    formulationVolume:'',
                    effectiveVolume:'',
                  },
                  {
                    id:'',
                    materialCode:'',
                    material:'',
                    moisture:'',
                    density:'',
                    formulationVolume:'',
                    effectiveVolume:'',
                  },
                  {
                    id:'',
                    materialCode:'',
                    material:'',
                    moisture:'',
                    density:'',
                    formulationVolume:'',
                    effectiveVolume:'',
                  },
                ]
              }
            ]
          };
        }else{
          this.model = Object.assign({}, record);
        }
        //备份model原始值
        this.modelDefault = JSON.parse(JSON.stringify(this.model));
        if(this.disabled){
          this.isEdit = false;
        }else{
          this.isEdit = true;
        }
        this.visible = true;
      },
      submitForm () {
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            httpAction(httpurl,this.model,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }
         
        })
      },
      addCavity(){
        if(!this.model.eneDistributions){
          this.$set(this.model,'eneDistributions',[])
        }
        this.model.eneDistributions.push({
          enePremixDistributions:[
            {
              id:'',
              materialCode:'',
              material:'',
              moisture:'',
              density:'',
              formulationVolume:'',
              effectiveVolume:'',
            },
            {
              id:'',
              materialCode:'',
              material:'',
              moisture:'',
              density:'',
              formulationVolume:'',
              effectiveVolume:'',
            },
            {
              id:'',
              materialCode:'',
              material:'',
              moisture:'',
              density:'',
              formulationVolume:'',
              effectiveVolume:'',
            },
            {
              id:'',
              materialCode:'',
              material:'',
              moisture:'',
              density:'',
              formulationVolume:'',
              effectiveVolume:'',
            },
          ]
        });
      },
      deleteCavity(originalIndex){
        let len = this.model.eneDistributions.length;
        if(len>1){
          this.model.eneDistributions.splice(originalIndex,1);
        }else{
          this.$message.error("最少保留一个预混分布！")
        }
      },
    },
    destroyed() {
      clearTimeout(this.timer);
      this.timer = null;
    },
  }
</script>
<style lang="scss" scoped>
.title{
  font-size: 24px;
  font-weight: bold;
}
.unit{
  padding-left: 4px;
  line-height: 40px;
}
.query-group-cust{
  width: 100%!important;
}
.ant-input-number{
  width: 100%!important;
}
.cavity-box{
  .title-box{
    height: 40px;
    padding: 0 5px;
    line-height: 40px;
    span{
      font-size: 24px;
      font-weight: bold;
      float: left;
    }
    .ant-btn-link{
      float: right;
    }
  }
  .mark-infos{
    position: relative;
    .editable-add-btn{
      position: absolute;
      top: 10px;
      right: 18px;
      z-index: 202;
    }
  }
}
</style>